function writeok = vmvwritepos(fid, vpos, usecol)
% vmvwritepos  - write one vertex movie position in a VMV file
%
% FORMAT:       writeok = vmvwritepos(fid, vpos, usecol)
%
% Input fields:
%
%       fid         1x1 file id (fopen, fread, fclose)
%       vpos        struct with at least the fields
%        .Coordinates  Cx3 coordinates
%        .Normals      Cx3 normals
%        .Colors       Cx4 SRF-like color coding (must be present if empty)
%       usecol      use colors in VMV
%
% Output fields:
%
%       writeok     boolean flag whether write succeeded

% Version:  v0.7f
% Build:    8110521
% Date:     Nov-05 2008, 9:00 PM CET
% Author:   Jochen Weber, SCAN Unit, Columbia University, NYC, NY, USA
% URL/Info: http://wiki.brainvoyager.com/BVQXtools

% check arguments
if nargin ~= 3 || ...
   ~isa(fid, 'double') || ...
    numel(fid) ~= 1 || ...
    isinf(fid) || ...
    isnan(fid) || ...
    fid < 1 || ...
    fid ~= fix(fid) || ...
   ~isstruct(vpos) || ...
    numel(vpos) ~= 1 || ...
   ~isfield(vpos, 'Coordinates') || ...
   ~isfield(vpos, 'Normals') || ...
   ~isequal(size(vpos.Coordinates), size(vpos.Normals)) || ...
   ~isfield(vpos, 'Colors') || ...
    numel(usecol) ~= 1 || ...
   (usecol && ...
    (size(vpos.Colors, 1) ~= size(vpos.Coordinates, 1) || ...
     size(vpos.Colors, 2) ~= 4 || ...
     ndims(vpos.Colors) ~= 2))
    error( ...
        'BVQXtools:BadArgument', ...
        'This call requires exactly 3 arguments.' ...
    );
end

% try/catch
try
    fpos = 0;
    if usecol
        rwwidth = 7;
    else
        rwwidth = 6;
    end
    nrc = size(vpos.Coordinates, 1);
    fpos = ftell(fid);
    tdat = single(zeros(nrc, rwwidth));
    tdat(:, 1:3) = vpos.Coordinates;
    tdat(:, 4:6) = vpos.Normals;
    fwrite(fid, tdat', 'single');
    if usecol
        fseek(fid, fpos, -1);
        tdat = fread(fid, [rwwidth, nrc], '*uint32')';
        fseek(fid, fpos, -1);
        tdat(:, 7) = colcode2uint32(vpos.Colors);
        fwrite(fid, tdat', 'uint32');
    end
catch
    error( ...
        'BVQXtools:InternalError', ...
        'Error reading movie position in file id %d at position %d.', ...
        fid, fpos ...
    );
end
